package loadiconhandler

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/pathutil"
	"strings"
)

type OpenInLoadIcon struct {
}

func (owner *OpenInLoadIcon) CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any) {
	urlMatch := strings.HasPrefix(req.Path, "openin:///") || strings.HasPrefix(req.Path, "openin://")
	if !urlMatch {
		return false, nil
	}
	parts := strings.Split(strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(req.Path, "openin:///"), "openin://")), "@@")
	if len(parts) < 2 {
		panic("openin协议格式有误")
	}
	file, dir := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
	if "" == file || "" == dir {
		panic("openin协议格式有误")
	}
	return true, []string{file, dir}
}

func (owner *OpenInLoadIcon) Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp {
	parts := extra.([]string)
	file, dir := parts[0], parts[1]

	fileParseResult := pathutil.ParseValidPath(file, req.CtxDir)
	if !fileParseResult.Succ || !fileParseResult.File {
		panic(fmt.Sprintf("文件不存在，无法打开：\r\n%s", file))
	}

	dirParseResult := pathutil.ParseValidPath(dir, "")
	if !dirParseResult.Succ || !dirParseResult.Dir {
		panic(fmt.Sprintf("目录不存在，无法打开：\r\n%s", dir))
	}
	return &vo.LoadIconResp{
		Cascade: true,
		Url:     GetFileIconUrl(appConfig, fileParseResult.ValidPath).Url,
		Url2:    SPECIAL_PATH_FOLDER,
	}
}
